<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="客户来源" prop="soureType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择客户来源" @change="sourceTypeChanged" style="width: 100%">
          <el-option
            v-for="dict in sourceOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="微信账号" prop="wechatNo" v-if="queryParams.sourceType==='1'">
        <el-input
          v-model="queryParams.wechatNo"
          placeholder="请输入微信账号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新媒体平台" prop="merchantPlatform" v-if="queryParams.sourceType==='2'">
        <el-select
          v-model="queryParams.merchantPlatform"
          placeholder="请选择新媒体平台类型"
          clearable
          style="width: 100%">
          <el-option
            v-for="dict in newMediaPlatOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商家账号" prop="merchantAccount" v-if="queryParams.sourceType==='2'">
        <el-input
          v-model="queryParams.merchantAccount"
          placeholder="请输入商家账号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺名称" prop="cusname">
        <el-input
          v-model="queryParams.cusname"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户等级" prop="level">
        <el-select v-model="queryParams.level" clearable>
          <el-option
            v-for="level in levelOptions"
            :key="level.dictValue"
            :label="level.dictLabel"
            :value="level.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户状态" prop="level">
        <el-select v-model="queryParams.status" clearable>
          <el-option
            v-for="status in statusOptions"
            :key="status.dictValue"
            :label="status.dictLabel"
            :value="status.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddCustom"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-sort-down"
          size="mini"
          :disabled="multiple"
          @click="handleAbandon"
        >放入公海</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-coordinate"
          size="mini"
          :disabled="multiple"
          @click="handleIntent"
        >意向标签</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-coordinate"
          size="mini"
          :disabled="multiple"
          @click="handleSign"
        >签约</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="roles.includes('admin') || roles.includes('leader')"
          type="success"
          icon="el-icon-coordinate"
          size="mini"
          :disabled="multiple"
          @click="handleHandover"
        >销售交接</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-coordinate"
          size="mini"
          v-if="roles.includes('admin') || roles.includes('leader')"
          :disabled="multiple"
          @click="handleAssign"
        >分配运营人员</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          v-hasPermi="['custom:custom:import']"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          v-if="roles.includes('admin') || roles.includes('leader')"
          @click="handleExportCustom"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="customList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50" fixed></el-table-column>
      <el-table-column label="微信账号" prop="wechatNo" min-width="130" :show-overflow-tooltip="true" align="center" v-if="queryParams.sourceType==='1'" />
      <el-table-column label="新媒体平台" prop="merchantPlatform" width="100" :show-overflow-tooltip="true" align="center" :formatter="newMediaPlatformFormat"  v-if="queryParams.sourceType==='2'"/>
      <el-table-column label="商家账号" prop="merchantAccount" width="120" :show-overflow-tooltip="true" align="center"  v-if="queryParams.sourceType==='2'||queryParams.sourceType==='1'"/>
      <el-table-column label="商家电话" prop="merchantTel" width="120" :show-overflow-tooltip="true" align="center"  v-if="queryParams.sourceType==='2'||queryParams.sourceType==='1'"/>
      <el-table-column label="电商平台" prop="platformType" width="100" :show-overflow-tooltip="true" align="center" :formatter="platformTypeFormat" />
      <el-table-column label="店铺名称" prop="cusname" min-width="160" :show-overflow-tooltip="true" header-align="center" />
      <el-table-column label="旺旺号" prop="aliww" width="140" align="left" header-align="center"/>
      <el-table-column label="所属类目" prop="groupName" width="150" align="left" header-align="center"/>
      <el-table-column label="销售人员" prop="allocationUserName" v-if="roles.includes('admin') || roles.includes('leader')" width="130" align="center" header-align="center"/>
      <el-table-column label="运营人员" prop="operators" v-if="roles.includes('admin') || roles.includes('leader')" width="160" align="left" header-align="center"/>
      <el-table-column label="客户状态" prop="status" align="center" width="110">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status=='0'">资源</el-tag>
          <el-tag v-if="scope.row.status=='1'">意向</el-tag>
          <el-tag type="success" v-if="scope.row.status=='2'">签约</el-tag>
          <el-tag type="danger" v-if="scope.row.status=='3'">沉默</el-tag>
          <el-tag type="danger" v-if="scope.row.status=='4'">流失</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" header-align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="left" header-align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditCustom(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.status=='0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteCustom(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleAddFollow(scope.row)"
          >跟进</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleShowContact(scope.row)"
          >联系人</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加联系人对话框 -->
<!--    <el-dialog :title="title" :visible.sync="openContactDialog" width="600px" append-to-body>-->
<!--      <el-form ref="contactForm" :model="contactForm" :rules="contactFormRules" label-width="80px">-->
<!--        <el-row :gutter="10">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="姓名" prop="name">-->
<!--              <el-input v-model.trim="contactForm.name" clearable placeholder="请输入联系人姓名" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="电话" prop="tel">-->
<!--              <el-input v-model.trim="contactForm.tel" clearable required placeholder="请输入电话" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row :gutter="10">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="性别" prop="sex">-->
<!--              <el-select v-model="contactForm.sex" clearable placeholder="请选择性别" style="width: 100%">-->
<!--                <el-option-->
<!--                  v-for="dict in sexOptions"-->
<!--                  :key="dict.dictValue"-->
<!--                  :label="dict.dictLabel"-->
<!--                  :value="dict.dictValue"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="生日" prop="birth">-->
<!--              <el-date-picker-->
<!--                v-model="contactForm.birth"-->
<!--                align="right"-->
<!--                type="date"-->
<!--                placeholder="请选择出生日期"-->
<!--                style="width: 100%"/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row :gutter="10">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="职务" prop="duties">-->
<!--              <el-input v-model.trim="contactForm.duties" clearable placeholder="请输入职务" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="微信" prop="wechat">-->
<!--              <el-input v-model.trim="contactForm.wechat" clearable placeholder="请输入微信号" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-row :gutter="10">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="QQ" prop="qq">-->
<!--              <el-input v-model.trim="contactForm.qq" clearable required placeholder="请输入QQ号" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitContactForm" v-prevent-re-click>确 定</el-button>-->
<!--        <el-button @click="cancelContactForm">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

    <!-- 查看联系人 -->
    <el-dialog :title="title" :visible.sync="showContactDialog" width="600px" :show-close="true" :close-on-click-modal="false" append-to-body>
      <el-table v-loading="loading" :data="contactList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="姓名" prop="name" min-width="120" align="center" />
        <el-table-column label="性别" prop="sex" width="80" align="center" :formatter="sexFormat"/>
        <el-table-column label="联系电话" prop="tel" min-width="150" align="center" />
      </el-table>
    </el-dialog>

    <!-- 放入公海 -->
    <el-dialog :title="title" :visible.sync="showAbandonDialog" width="600px" :show-close="true" :close-on-click-modal="false" append-to-body>
      <el-form ref="abandonForm" :model="abandonForm" :rules="abandonFormRules" label-width="100px">
        <el-form-item label="放弃原因" prop="reason">
          <el-input type="textarea" v-model="abandonForm.reason" palceholder="请填写放弃原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAbandon" v-prevent-re-click>确 定</el-button>
        <el-button @click="cancelAbandon">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加跟进记录 -->
    <el-dialog :title="title" :visible.sync="openAddFollowDialog" width="600px" :close-on-click-modal="false" append-to-body>
      <el-form ref="followForm" :model="followForm" :rules="followFormRules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="跟进记录" prop="content">
              <el-input type="textarea" v-model="followForm.content"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="followForm.contact"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="followForm.tel"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFollowForm">确 定</el-button>
        <el-button @click="cancelFollowForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户交接 -->
    <el-dialog :title="title" :visible.sync="openAddHandoverDialog" width="600px" :close-on-click-modal="false" append-to-body>
      <el-form ref="handoverForm" :model="handoverForm" :rules="handoverFormRules" label-width="80px">
        <el-form-item label="交接给" prop="userId">
          <el-cascader
            v-model="handoverForm.deptUser"
            :options="userOptions"
            :normalizer="user_normalizer"
            @change="handleChangeUser"
            style="width: 100%"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandoverForm">确 定</el-button>
        <el-button @click="cancelHandoverForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配运营人员 -->
    <el-dialog :title="title" :visible.sync="showAssignOperator" width="920px" :close-on-click-modal="false" append-to-body>
      <el-form :model="assignForm" ref="assignForm" style="margin-left: 20px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="运营人员" prop="operators">
              <el-cascader
                v-model="assignForm.operators"
                :options="userOptions"
                :props="props"
                :normalizer="user_normalizer"
                filterable
                style="width: 87%"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssignOperatorForm">确 定</el-button>
        <el-button @click="cancelAssignOperatorForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog :title="title" :visible.sync="showImport" width="450px" append-to-body>
      <div style="margin-left: 20px">
        <el-upload
          ref="importUpload"
          class="upload-demo"
          drag
          action=""
          accept=".xls,.xlsx"
          :multiple="importMultiple"
          :limit="importLimit"
          :file-list="importFileList"
          :http-request="handleImportExcel"
          :on-remove="handleRemoveImportFile"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" style="margin-top: 20px" slot="tip">只能上传.xls/.xlsx文件</div>
        </el-upload>
        <div class="el-upload__tip" style="color: #76BEFF;cursor: pointer;margin-top: 10px;margin-bottom: 20px" @click="downLoadExcel">下载模板</div>
        <div v-if="importChargeError.length > 0" style="margin-top: 20px">
          <h3>错误信息：</h3>
          <p v-for="item in importChargeError" style="font-size: 12px; color: red">{{item}}</p>
        </div>
        <el-row :gutter="10">
          <el-col :span="23" style="text-align: right;margin-top: 20px">
            <el-button @click="handleCloseImportWindow">取消</el-button>
            <el-button type="primary" @click="handleSubmitImportForm" v-preventReClick>确定</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 添加类目 -->
    <el-dialog :title="title" :visible.sync="showAddGroup" width="600px" append-to-body>
      <el-form ref="groupForm" :model="groupForm" :rules="groupFormRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分组" prop="parentId">
              <treeselect
                v-model="groupForm.parentId"
                :options="parentGroupOptions"
                :normalizer="group_normalizer"
                :show-count="true"
                placeholder="选择上级类目"
                :flat="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="类目名称" prop="groupName">
              <el-input v-model.trim="groupForm.groupName" placeholder="请输入类目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排序" prop="corder">
              <el-input-number v-model.trim="groupForm.corder" placeholder="请输入排序" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGroupForm">确 定</el-button>
        <el-button @click="cancelGroup">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增客户 -->
    <addcustom
      :dialogVisble="openAddCustomDialog"
      title="创建客户"
      menu="custom"
      :active="active"
      @closeAddCustomDialog="closeAddCustomDialog"></addcustom>

    <!-- 编辑客户 -->
    <editcustom
      :dialogVisble="openEditCustomDialog"
      title="修改客户"
      menu="custom"
      :data-model="customForm"
      :active="active"
      @closeEditCustomDialog="closeEditCustomDialog"></editcustom>

  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "@/assets/styles/vue-treeselect.css";
import { addGroup, deleteGroup, listGroup } from '@/api/custom/group/group'
import {parseTime} from "../../utils/ruoyi";
import {
  abandonCustom,
  addContact,
  addCustom, assignOperators, deleteContact, deleteCustom, exportCustom,
  getContactInfo,
  getCustomInfo, handoverCustom, importExcel, insertCommunication, insertFollow, intentCustom, intentCustoms,
  listContact,
  listCustom, selectCommunication, selectFollow, signCustom, signCustoms,
  updateContact, updateCustom
} from '@/api/custom/custom'
import { exportUser, listUser, selectAllDeptUser } from '@/api/system/user'
import { mapGetters } from 'vuex'
import addcustom from '@/views/shop/component/addcustom.vue'
import editcustom from '@/views/shop/component/editcustom.vue'

export default {
  name: "Custom",
  components: { editcustom, addcustom, Treeselect},
  data() {
    return {
      active: 1,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 客户列表
      customList: [],
      // 弹出层标题
      title: '',
      // 是否显示添加客户弹出层
      openAddCustomDialog: false,
      // 是否显示修改客户弹出层
      openEditCustomDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceType: '0',
        wechatNo: '',
        merchantPlatform: '',
        merchantAccount: '',
        cusname: '',
        level: '',
        status: ''
      },
      // 分组列表
      groupList: [],
      // 分组树选项
      groupOptions: [],
      group_props: { multiple: false },
      props: { multiple: true },
      // 平台类型选项
      platformOptions: [],
      // 客户等级选项
      levelOptions: [],
      // 客户状态选项
      statusOptions: [],
      // 客户表单
      customForm: {
        id: '',
        platformType: '',
        cusname: '',
        level: '',
        groupName: '',
        company: '',
        adddress: '',
        industryId: '',
        allocation_status: '',
        allocation_userid: '',
        allocation_time: '',
        status: '0',
        operStatus: '0',
        contact_name: '',
        contact_sex: '',
        contact_birth: '',
        contact_duties: '',
        contact_tel: '',
        contact_wechat: '',
        contact_qq: '',
        contact_aliww: '',
        contacts: [],
        groups: []
      },
      // 所属行业选项
      industryOptions: [],
      // 性别选项
      sexOptions: [],
      // 客户表单校验项
      customFormRules: {
        cusname: [
          { required: true, message: "店铺名称不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 50, message: '长度应该为1-50个字符', trigger: ['blur', 'change'] }
        ],
        platformType: [
          { required: true, message: "平台类型必须选择", trigger: ['blur', 'change'] }
        ],
        level: [
          { required: true, message: "客户等级必须选择", trigger: ['blur', 'change'] }
        ],
        groupName: [
          { required: true, message: "所属类目不能为空", trigger: ['blur', 'change'] }
        ],
        contact_name: [
          { required: true, message: "联系人姓名不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 10, message: '长度应该为1-10个字符', trigger: ['blur', 'change'] }
        ],
        contact_tel: [
          { required: true, message: "联系人电话不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 20, message: '长度应该为1-20个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 联系人标题
      contactTile: '添加联系人',
      // 是否打开添加联系人
      openContactDialog: false,
      // 是否显示放入公海窗体
      showAbandonDialog: false,
      // 放入公海表单
      abandonForm: {
        ids: [],
        reason: ''
      },
      // 放入公海表单校验
      abandonFormRules: {
        reason: [
          { required: true, message: "放弃原因必须填写", trigger: ['blur', 'change'] },
          { min:1, max: 100, message: '长度应该为1-100个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 联系人表单
      contactForm: {
        id: '',
        customId: '',
        name: '',
        sex: '',
        birth: '',
        duties: '',
        tel: '',
        wechat: '',
        qq: '',
        aliww: ''
      },
      // 联系人表单校验规则
      contactFormRules: {
        name: [
          { required: true, message: "联系人姓名不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 10, message: '长度应该为1-10个字符', trigger: ['blur', 'change'] }
        ],
        tel: [
          { required: true, message: "联系人电话不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 20, message: '长度应该为1-20个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 是否打开添加跟进记录
      openAddFollowDialog: false,
      openFollowDialog1: false,
      // 跟进记录表单
      followForm: {
        id: '',
        customId: '',
        contact: '',
        content: '',
        tel: '',
        intention: '',
        method: '',
        nextTime: undefined
      },
      // 添加跟进记录表单教校验
      followFormRules: {
        content: [
          { required: true, message: "跟进内容不能为空", trigger: ['blur', 'change'] },
          { min:1, max: 500, message: '长度应该为1-500个字符', trigger: ['blur', 'change'] }
        ],
        // contact: [
        //   { required: true, message: '联系人不能为空', trigger: ['blur', 'change'] },
        //   { min: 1, max: 30, message: '联系人长度应为1-30个字符', trigger: ['blur', 'change'] }
        // ],
        // method: [
        //   { required: true, message: '跟进方式不能为空', trigger: 'change' }
        // ]
      },
      // 跟进记录
      follows: [],
      // 跟进方式
      followMehtodOptions: [],
      // 客户交接表单
      handoverForm: {
        userId: undefined,
        customIds: [],
        deptUser: []
      },
      openAddHandoverDialog: false,
      handoverFormRules: {
        userId: [
          { required: true, message: "交接用户必须选择", trigger: 'change' }
        ]
      },
      userOptions: [],

      // 显示分配运营人员窗口
      showAssignOperator: false,
      assignForm: {
        id: '',
        customIds: [],
        operators: []
      },
      showImport: false,
      importMultiple: false,
      importLimit: 1,
      importFileList: [],
      importChargeError: [],
      formData: new FormData(),
      // 是否显示添加类目对话框
      showAddGroup: false,
      // 上级类目
      parentGroupOptions: [],
      // 类目表单
      groupForm: {
        id: null,
        groupName: '',
        parentId: null,
        fullId: '',
        fullGroupName: '',
        corder: 0,
        status: '1'
      },
      // 类目表单校验
      groupFormRules: {
        parentId: [
          { required: true, message: '上级分组不能为空', trigger: 'change'}
        ],
        groupName: [
          { required: true, message: "类目名称不能为空", trigger: "blur" }
        ]
      },
      // 客户来源选项
      sourceOptions: [],
      // 新媒体类型选项
      newMediaPlatOptions: [],
      // 是否显示联系人
      showContactDialog: false,
      // 联系人
      contactList: []
    }
  },
  computed:{
    ...mapGetters([
      'userid',
      'name',
      'roles'
    ])
  },
  created() {
    this.getDicts("custom_platform").then(response => {
      this.platformOptions = response.data;
    })
    this.getDicts("custom_level").then(response => {
      this.levelOptions = response.data;
    })
    this.getDicts("custom_status").then(response => {
      this.statusOptions = response.data;
    })
    this.getDicts("custom_industry").then(response => {
      this.industryOptions = response.data;
    })
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    })
    this.getDicts("follow_type").then(response => {
      this.followMehtodOptions = response.data
    })
    this.getDicts("custom_source").then(response => {
      this.sourceOptions = response.data;
    })
    this.getDicts("new_media_platform").then(response => {
      this.newMediaPlatOptions = response.data;
    })
    this.getList()
  },
  methods: {
    parseTime,
    // 查询
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 查询方法
    getList() {
      this.loading = true;
      listCustom(this.queryParams).then(response => {
          this.customList = response.rows
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 客户等级格式化
    levelFormat(row) {
      return this.selectDictLabel(this.levelOptions, row.level);
    },
    // 平台类型格式化
    platformTypeFormat(row) {
      return this.selectDictLabel(this.platformOptions, row.platformType);
    },
    // 新媒体平台格式化
    newMediaPlatformFormat(row){
      return this.selectDictLabel(this.newMediaPlatOptions, row.merchantPlatform);
    },
    // 客户分组格式化
    groupFormat(row) {
      var group = this.groupOptions.find(item => item.id === row.groupId)
      if(group === undefined || group == null){
        return '主类目'
      }

      return group.groupName
    },
    // 所属行业格式化
    industryFormat(row) {
      var industryItem = this.industryOptions.find(item => item.dictValue === row.industry)
      if(industryItem === undefined) {
        return ''
      }
      return industryItem.dictLabel
    },
    // 分配状态格式化
    allocationStatusFormat(row) {
      if(row.allocationStatus === "1") {
        return '已分配'
      } else {
        return '未分配'
      }
    },
    // 客户状态格式化
    statusFormat(row) {
      if(row.status === '0') {
        return '资源'
      } else if(row.status === '1') {
        return '意向'
      } else if(row.status === '2') {
        return '签约'
      } else if(row.status === '3') {
        return '沉默'
      } else if(row.status === '4') {
        return '流失'
      } else {
        return '未知'
      }
    },
    // 性别格式化
    sexFormat(row) {
      if(row.sex === '0') {
        return '男'
      } else if(row.sex === '1') {
        return '女'
      } else {
        return '未知'
      }
    },
    // 重置查询条件
    resetQuery() {

    },
    // 转换菜单数据结构
    group_normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.groupName,
        children: node.children
      };
    },
    user_normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.userId,
        label: node.nickName,
        children: node.children
      }
    },

    // 查询部门用户树
    selectDeptUserTree(){
      selectAllDeptUser().then(response => {
        this.userOptions = this.handleTree(response.data, "userId");
      })
    },
    // 查询分组下拉树结构
    getTreeselect() {
      listGroup().then(response => {
        this.groupList = response.data
        let groups = []

        response.data.forEach(item => {
          let data = {}
          data.value = item.id
          data.label = item.groupName
          data.parentId = item.parentId
          groups.push(data)
        })
        this.groupOptions = this.handleTree(groups, "value");
      });
    },
    // 重置表单
    resetCustomForm() {
      this.customForm = {
        id: '',
        platformType: '',
        cusname: '',
        level: '',
        groupName: '',
        company: '',
        adddress: '',
        industryId: '',
        allocation_status: '',
        allocation_user: '',
        allocation_time: '',
        status: '0',
        contacts: [{
          id: '',
          customId: '',
          name: '',
          sex: '',
          birth: '',
          duties: '',
          tel: '',
          wechat: '',
          qq: '',
          aliww: '',
          isdefault: '1'
      }]
      }
      this.resetForm('customForm')
    },
    // 新增客户
    handleAddCustom() {
      this.openAddCustomDialog = true
      this.active = 1
    },
    // 关闭创建客户弹窗
    closeAddCustomDialog(value) {
      this.openAddCustomDialog = false
      if(value) {
        this.getList()
      }
    },
    // 修改客户
    handleEditCustom(row) {
      getCustomInfo(row.id).then(response => {
        this.customForm = response.data
        this.openEditCustomDialog = true
      })

      // getCustomInfo(row.id).then(response => {
      //   if(response.code === 200) {
      //     this.customForm = response.data;
      //     this.openEditCustomDialog = true;
      //     this.title = '修改客户'
      //   }
      // })
    },
    // 关闭修改客户弹窗
    closeEditCustomDialog(value) {
      this.openEditCustomDialog = false
      if(value) {
        this.getList()
      }
    },
    // 放入公海
    handleAbandon() {
      if(this.ids.length === 0) {
        this.msgError('请选择要放入公海的客户！')
        return
      }

      for(let i = 0; i < this.customList.length; i++){
        if(this.ids.includes(this.customList[i].id) && this.customList[i].status === '2') {
          this.$message.warning('已签约客户不允许放入公海，请检查！')
          return
        }
      }
      this.resetAbandon()
      this.abandonForm.ids = this.ids
      this.title = '放入公海'
      this.showAbandonDialog = true


      // const that = this
      // this.$confirm('您已勾选' + this.ids.length + '条数据，', "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // }).then(function() {
      //   return abandonCustom(that.ids)
      // }).then(response => {
      //   this.getList()
      //   this.msgSuccess("操作成功");
      // })
    },
    // 客户交接
    handleHandover() {
      if(this.ids.length === 0) {
        this.msgError('请选择要交接的客户！')
        return
      }
      const that = this
      selectAllDeptUser().then(response => {
        this.handoverForm.customIds = this.ids
        this.userOptions = this.handleTree(response.data, "userId");
        this.resetHandoverForm()
        this.title = '客户交接'
        this.openAddHandoverDialog = true
        this.getList()
      })
    },
    // // 意向标签
    // handleIntent(row) {
    //   this.$confirm('是否确认将该客户标记为意向客户？', "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   }).then(function() {
    //     return intentCustom(row.id)
    //   }).then(response => {
    //     this.getList()
    //     this.msgSuccess("操作成功");
    //   })
    // },
    handleIntent() {
      for(let i = 0; i < this.ids.length; i++){
        const custom = this.customList.find(f=>f.id === this.ids[i])
        if(custom.status !== '0'){
          this.$message.warning('只有“资源”户才能添加意向标签，请检查！')
          return
        }
      }

      const that = this
      this.$confirm('您已选择' + this.ids.length + '条数据，是否确认添加意向标签？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        return intentCustoms(that.ids)
      }).then(response=>{
        this.getList()
        this.msgSuccess("操作成功");
      })
    },
    // 删除客户
    handleDeleteCustom(row) {
      this.$confirm('是否确认删除名称为"' + row.cusname + '"的客户?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteCustom(row.id);
      }).then(() => {
        this.getList()
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },

    handleImport() {
      this.title = '导入'
      this.formData.delete('file')
      this.importFileList = []
      this.importChargeError = []
      this.showImport = true
    },
    // 导出客户
    handleExportCustom() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportCustom(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 提交表单
    submitForm() {
      this.$refs['customForm'].validate(valid => {
        if (valid) {
          if(this.customForm.id === undefined || this.customForm.id === '') {
            var obj = {}
            obj.name = this.customForm.contact_name
            obj.sex = this.customForm.contact_sex
            obj.birth = this.customForm.contact_birth
            obj.duties = this.customForm.contact_duties
            obj.tel = this.customForm.contact_tel
            obj.wechat = this.customForm.contact_wechat
            obj.qq = this.customForm.contact_qq
            obj.aliww = this.customForm.contact_aliww
            this.customForm.contacts = []
            this.customForm.contacts.push(obj)

            addCustom(this.customForm).then(response=>{
              if(response.code === 200) {
                this.msgSuccess("新增成功");
                this.openAddCustomDialog = false;
                this.getList();
              }
            })
          }else {
            updateCustom(this.customForm).then(response => {
              this.msgSuccess("修改成功");
              this.openEditCustomDialog = false;
              this.getList();
            })
          }
        }
      })
    },
    // 关闭弹层
    cancel() {
      this.resetCustomForm()
      this.openAddCustomDialog = false;
      this.openEditCustomDialog = false;
    },
    // 查询联系人
    getContactList() {
      listContact(this.customForm.id).then(response =>{
        this.customForm.contacts = response.rows
      })
    },
    // 修改联系人
    handleUpdateContact(row) {
      getContactInfo(row.id).then(response => {
        if(response.code === 200) {
          this.contactForm = response.data
          this.openContactDialog = true
          this.contactTile = '修改联系人'
        }
      })
    },
    // 删除联系人
    handleDeleteContact(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的联系人?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteContact(row.id);
      }).then(() => {
        this.getContactList()
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    // 添加联系人
    handleAddContact() {
      this.resetContactForm()
      this.openContactDialog = true
      this.contactTile = '添加联系人'
    },
    // 重置联系人表单
    resetContactForm() {
      this.contactForm = {
        id: '',
        customId: '',
        name: '',
        sex: '',
        birth: '',
        duties: '',
        tel: '',
        wechat: '',
        qq: '',
        aliww: ''
      }
      this.resetForm('contactForm')
    },
    submitAbandon() {
      this.$refs['abandonForm'].validate(valid => {
        if(valid){
          abandonCustom(this.abandonForm).then(response => {
            this.$message.success('放入公海成功！')
            this.getList()
            this.showAbandonDialog = false
          })
        }
      })
    },
    cancelAbandon() {
      this.showAbandonDialog = false
      this.resetAbandon()
    },
    resetAbandon() {
      this.abandonForm = {
        ids: [],
        reason: ''
      }
      this.resetForm('abandonForm')
    },
    // 提交联系人表单
    submitContactForm() {
      this.$refs['contactForm'].validate(valid => {
        if(valid) {
          if(this.contactForm.id === undefined || this.contactForm.id === ''){
            this.contactForm.customId = this.customForm.id
            addContact(this.contactForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.openContactDialog = false;
                this.getContactList()
                // this.contactForm.id= response.data;
                // this.contactForm.birth = parseTime(this.contactForm.birth, '{y}-{m}-{d}')
                // this.customForm.contacts.push(this.contactForm)
              }
            })
          } else {
            updateContact(this.contactForm).then(response => {
              if(response.code === 200) {
                this.msgSuccess("修改成功");
                this.openContactDialog = false;
                this.getContactList()
              }
            })
          }
        }
      })
    },
    // 关闭联系人表单
    cancelContactForm() {
      this.resetContactForm()
      this.openContactDialog = false;
    },

    // 跟进
    handleFollow(row){
      this.followForm.customId= row.id
      selectFollow(row.id).then(response => {
        this.follows = response.data
        this.title = '跟进记录'
        this.openAddFollowDialog = true
      })
    },
    // 打开添加跟进记录窗口
    handleAddFollow(row){
      this.followForm.customId= row.id
      this.title = '跟进记录'
      this.openAddFollowDialog = true
    },
    // 打开联系人对话框
    handleShowContact(row){
      listContact(row.id).then(response=>{
        this.contactList = response.rows
        this.title = '联系人'
        this.showContactDialog = true
      })
    },
    // 签约客户
    handleSign(){
      for(let i = 0; i < this.ids.length; i++){
        const custom = this.customList.find(f=>f.id === this.ids[i])
        if(custom.status === '2'){
          this.$message.warning('您勾选的数据中包含已签约客户，请检查！')
          return
        }
      }

      const that = this
      this.$confirm('您已勾选' + this.ids.length + '条数据，是否确认签约该客户？', '提示', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return signCustoms(that.ids)
      }).then(response => {
        this.msgSuccess('客户签约成功！')
        this.getList()
      })
    },
    // 重置跟进记录表单
    resetFollowForm(){
      this.followForm.id = ''
      this.followForm.customId = ''
      this.followForm.content = ''
      this.followForm.contact = ''
      this.followForm.method = ''
      this.resetForm('followForm')
    },
    // 提交跟进记录表单
    submitFollowForm(){
      this.$refs['followForm'].validate(valid=>{
        if(valid){
          if(this.followForm.id === undefined || this.followForm.id === ''){
            let that = this
            this.$confirm('跟进记录保存后无法修改，是否继续保存？', '提示', {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function(){
              insertFollow(that.followForm).then(response => {
                if(response.code === 200){
                  that.msgSuccess("新增成功");
                  that.openAddFollowDialog = false
                  that.resetFollowForm()
                }
              })
            })
          }
        }
      })
    },
    // 重置客户交接表单
    resetHandoverForm() {
      //this.handoverForm.customIds = []
      this.handoverForm.userId = undefined
      this.handoverForm.deptUser = []
      this.resetForm('handoverForm')
    },
    // 关闭跟进记录表单
    cancelFollowForm(){
      this.openAddFollowDialog = false
      this.resetFollowForm()
    },
    // 切换交接人
    handleChangeUser() {
      this.handoverForm.userId = this.handoverForm.deptUser[this.handoverForm.deptUser.length - 1]
    },
    // 提交客户交接表单
    submitHandoverForm() {
      this.$refs.handoverForm.validate(valid => {
        if(valid) {
          handoverCustom(this.handoverForm).then(response => {
            if(response.code === 200) {
              this.msgSuccess('客户交接成功！')
              this.resetHandoverForm()
              this.openAddHandoverDialog = false
            }
          })
        }
      })
    },
    // 关闭客户交接窗口
    cancelHandoverForm(){
      this.resetHandoverForm()
      this.openAddHandoverDialog = false
    },
    // 分配运营人员
    handleAssign() {
      for(let i = 0; i < this.ids.length; i++){
        const custom = this.customList.find(f=>f.id === this.ids[i])
        if(custom.status !== '2'){
          this.$message.warning('只有已签约的店铺可以分配给运营人员，请检查！')
          return
        }
      }

      this.selectDeptUserTree()
      this.title = '分配运营人员'
      this.showAssignOperator = true
      this.resetAssignForm()
      this.assignForm.customIds = this.ids
    },

    resetAssignForm(){
      this.assignForm.id = ''
      this.assignForm.customIds = ''
      this.assignForm.operators = []
      this.resetForm('assignForm')
    },
    submitAssignOperatorForm() {
      let params = {}
      params.customIds = this.assignForm.customIds
      params.operators = []
      if(this.assignForm.operators !== null && this.assignForm.operators.length > 0){
        this.assignForm.operators.forEach(o=>{
          params.operators.push(o[o.length - 1])
        })
      }else{
        this.$message.warning('请选择运营人员！')
        return
      }

      this.$refs.assignForm.validate(valid => {
        if(valid){
          this.$confirm('是否确认将店铺分配给勾选的人员？', '提示', {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function(){
            return assignOperators(params)
          }).then(response => {
            this.$message.success('分配成功！')
            this.showAssignOperator = false
            this.resetAssignForm()
            this.getList()
          })
        }
      })
    },
    cancelAssignOperatorForm() {
      this.showAssignOperator = false
      this.resetAssignForm()
    },
    handleImportExcel(data) {
      this.formData.append('file', data.file)
    },
    handleRemoveImportFile() {
      this.formData.delete('file')
    },
    downLoadExcel() {
      let a = document.createElement('a')
      a.href = '/客户信息导入模板.xlsx'
      a.download = '客户信息导入模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    handleCloseImportWindow() {
      this.$data.showImport = false
      this.$data.formData = new FormData()
    },
    handleSubmitImportForm() {
      this.$data.importChargeError = [];
      if(!this.$data.formData.has("file")){
        this.$message.error("请选择要导入的文件");
        return;
      }
      if (!(this.$data.formData.get("file").type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        this.$data.formData.get("file").type == 'application/vnd.ms-excel')) {
        this.$message.error('上传文件只能是xlsx和xls格式的文件！')
        return
      }
      const isMax = this.$data.formData.get("file").size  >= 20971520
      if (isMax) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '正在导入报考信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      importExcel(this.formData).then(response => {
        if(loading) loading.close()

        console.log('导入结果：' + JSON.stringify(response.data))
        if (response.data.code === 1){
          this.msgSuccess('导入成功')
          this.formData = new FormData()
          this.showImport = false
          this.getList()
        }else{
          if (response.data != null && response.data.msg != null) {
            response.data.msg.forEach(item => {
              this.importChargeError.push(item)
            })
            this.formData.delete('file')
            this.importFileList = []
          }
        }
      }).catch(e => {
        if(loading) loading.close()
        this.formData.delete('file')
        this.importFileList = []
        this.importChargeError = []
      })
    },
    // 打开添加类目对话框
    handleAddGroup() {
      this.title = '添加类目'
      this.resetGroupForm()
      this.getCurrentGroupTree()
      this.showAddGroup = true
    },
    // 获取当前类目
    getCurrentGroupTree() {
      listGroup().then(response => {
        this.parentGroupOptions = [];
        const group = { id: 0, groupName: '主类目', children: [] };
        group.children = this.handleTree(response.data, "id");
        this.parentGroupOptions.push(group);
      });
    },
    // 提交类目表单
    submitGroupForm() {
      this.$refs["groupForm"].validate(valid => {
        if(valid) {
          addGroup(this.groupForm).then(response=>{
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.showAddGroup = false;
              this.resetGroupForm()
              this.getTreeselect()
            }
          })
        }
      })
    },
    // 关闭类目表单
    cancelGroup() {
      this.resetGroupForm()
      this.showAddGroup = false
    },
    // 重置类目表单
    resetGroupForm() {
      this.groupForm.id = null
      this.groupForm.groupName = ''
      this.groupForm.parentId = null
      this.groupForm.fullId = ''
      this.groupForm.fullGroupName = ''
      this.groupForm.corder = 0
      this.groupForm.status = '1'
      this.resetForm("groupForm")
    },
    // 切换客户来源
    sourceTypeChanged(){
      if(this.queryParams.sourceType === '0'){
        this.queryParams.wechatNo = ''
        this.queryParams.merchantPlatform = ''
        this.queryParams.merchantAccount = ''
      }else if(this.queryParams.sourceType === '1'){
        this.queryParams.merchantPlatform = ''
        this.queryParams.merchantAccount = ''
      }else if(this.queryParams.sourceType === '2'){
        this.queryParams.wechatNo = ''
      }
      this.getList()
    }
  }
}
</script>


<style>



</style>
